/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2019-03-08     obito0       first version
 */

#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>

#ifdef RT_USING_DFS
#include <dfs.h>
#include <dfs_fs.h>
#include <dfs_file.h>
//#include "dfs_posix.h"
#endif
#ifdef RT_USING_SPI
#include "drv_spi.h"
#endif
#ifdef RT_USING_SFUD
#include "spi_flash_sfud.h"
#endif

void filesysytem_try_mount(char *device_name, char *mount_point, char *fs_type_name, int mkfs_count)
{
	struct statfs fs_stat;
	int rc = 0;

	rt_kprintf("mount(\"%s\",\"%s\",\"%s\");\n", device_name, mount_point, fs_type_name);

	if (rt_device_find(device_name) == NULL)
	{
		rt_kprintf("%s not find!!!\n", device_name);
		return;
	}
	mkdir(mount_point, 0);
_remount:
	rc = dfs_mount(device_name, mount_point, fs_type_name, 0, 0);
	if (rc == 0)
	{
		rt_kprintf("mounted %s on %s\n", device_name, mount_point);
		if (statfs(mount_point, &fs_stat) >= 0)
		{
			rt_kprintf("%s size:%d, total: %d, free: %d \n", mount_point,
								 fs_stat.f_bsize, fs_stat.f_blocks, fs_stat.f_bfree);
		}
	}
	else
	{
		if (mkfs_count > 0)
		{
			rt_kprintf("[%s]try mkfs -t %s %s \n", mkfs_count, fs_type_name, device_name);
			dfs_mkfs(fs_type_name, device_name);
			mkfs_count--;
			goto _remount;
		}
		rt_kprintf("mount failed :%d \n", rc);
	}
}


#include "drv_spi.h"
#include <drivers/spi.h>
#include "spi_msd.h"

static int rt_hw_spi1_tfcard(void)
{
    __HAL_RCC_GPIOA_CLK_ENABLE();
    rt_hw_spi_device_attach("spi1", "spi10", GPIOA, GPIO_PIN_4);
    return msd_init("sd0", "spi10");
}
INIT_DEVICE_EXPORT(rt_hw_spi1_tfcard);


/* defined the LED0 pin: PC13 */
#define LED0_PIN    GET_PIN(C, 13)

int main(void)
{
    /* set LED0 pin mode to output */
    rt_pin_mode(LED0_PIN, PIN_MODE_OUTPUT);
	
		filesysytem_try_mount("sd0","/","elm",3);

    while (1)
    {
        rt_pin_write(LED0_PIN, PIN_HIGH);
        rt_thread_mdelay(500);
        rt_pin_write(LED0_PIN, PIN_LOW);
        rt_thread_mdelay(500);
    }
}
